package com.yikome.storehouse.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.base.Preconditions;
import com.itmuch.lightsecurity.annotation.PreAuthorize;
import com.yikome.constant.CommonConstant;
import com.yikome.mq.purchase.request.PurchaseStorageProductRequest;
import com.yikome.storehouse.dto.InventoryDTO;
import com.yikome.storehouse.dto.RemoteClearStorehouseCheckRequest;
import com.yikome.storehouse.dto.StorehouseTreeGrid;
import com.yikome.storehouse.entity.Storehouse;
import com.yikome.storehouse.request.InventoryEditRequest;
import com.yikome.storehouse.request.InventoryRequest;
import com.yikome.storehouse.service.StorehouseService;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/admin/storehouse")
public class StorehouseController {

	@Autowired
	private StorehouseService storehouseService ; 
	
	/**
	 * 获取仓库treegird数据
	 */
	@GetMapping("/tree-list")
	@PreAuthorize("hasLogin()")
	public List<StorehouseTreeGrid> findStorehouseTreeGrid(){
		
		return storehouseService.findStorehouseTreeGrid();
		
	}
	
	/**
	 * 获取仓库combobox数据,---提供查询使用
	 */
	@GetMapping("/combo")
	@PreAuthorize("hasLogin()")
	public List<Map<String , Object>> findStorehouseCombo(){
		
		return storehouseService.findStorehouseCombo();
		
	}
	
	/**
	 * 新增或修改仓库
	 */
	@PostMapping
	@PreAuthorize("hasAnyRoles('admin')")
	public Storehouse peristStorehouse(@RequestBody Storehouse storehouse) {
		
		return storehouseService.save(storehouse);
	}
	
	/**
	 * 删除仓库
	 */
	@DeleteMapping("/{storehouseId}")
	@PreAuthorize("hasAnyRoles('admin')")
	public boolean deleteStorehouseId(@PathVariable("storehouseId") Long storehouseId) {
		
		storehouseService.deleteStorehouseId(storehouseId);
		
		return Boolean.TRUE ;
	}
	
	/***************************************************************************************************************************************************/
	
	/**
	 * 条件查询库存数据,
	 * productSkuBarcode,
	 * storehouseId,
	 */
	@GetMapping("/inventory")
	@PreAuthorize("hasAnyRoles('admin', 'purchase', 'analysis', 'storehouse', 'finance', 'order')")
	public Page<InventoryDTO> findInventoryDTO(InventoryRequest inventoryRequest , @PageableDefault(direction = Direction.DESC , sort = {"s_inventory.storehouse_id" , "s_inventory.inventory"})Pageable pageable){
		
		return storehouseService.findInventoryDTO(inventoryRequest , pageable);
	}
	
	/**
	 * 条件库存数据导出
	 * @throws Exception 
	 */
	@GetMapping("/inventory/export")
	@PreAuthorize("hasAnyRoles('admin', 'analysis', 'storehouse', 'finance')")
	public String exportInventoryDTO(InventoryRequest inventoryRequest) throws Exception{
		
		Page<InventoryDTO> contents = storehouseService.findInventoryDTO(inventoryRequest , PageRequest.of(0, 1000000, Direction.DESC, "s_inventory.storehouse_id" , "s_inventory.inventory"));
		
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("库存明细", "库存明细"), InventoryDTO.class, CollectionUtil.newArrayList(contents.getContent()));
        
    	String folderPath = CommonConstant.BASE_LOCATION + LocalDateTime.now(ZoneId.of("+8")).format(CommonConstant.DATETIMEFORMATTRT_DATE) + '/' ;
		File fileFolder = new File(folderPath);
		if (!fileFolder.exists())fileFolder.mkdirs();
		
		String fileName = LocalDateTime.now(ZoneId.of("+8")).format(CommonConstant.DATETIMEFORMATTRT_TIME) + "-库存明细.xlsx" ;
		
		String filePath = folderPath + fileName ;
		FileOutputStream fos = new FileOutputStream(filePath);
		workbook.write(fos);
        fos.close();
		return filePath ; 
	}
	
	@PutMapping("/inventory/edit")
	@PreAuthorize("hasAnyRoles('admin', 'storehouse', 'purchase')")
	public List<InventoryEditRequest> editInventory(@RequestBody List<InventoryEditRequest> inventoryEditRequests) throws Exception{
		
		List<InventoryEditRequest> errors = new ArrayList<>();
		
		for (InventoryEditRequest inventoryEditRequest : inventoryEditRequests) {
			
			try {
				Preconditions.checkArgument(inventoryEditRequest.getStorehouseId() != null, "仓库ID不存在...");
				Preconditions.checkArgument(inventoryEditRequest.getQuantity() != null, "库存数量不存在...");
				Preconditions.checkArgument(StrUtil.isNotBlank(inventoryEditRequest.getProductSkuBarcode()), "商品编码不存在...");
				
				storehouseService.editInventory(inventoryEditRequest);
				
			}catch (Exception e) {
				inventoryEditRequest.setErrorMsg(e.getMessage());
				errors.add(inventoryEditRequest);
			}
		}
		return errors;
	}
	
	/**
	 * ?salt=0ba4439ee9a46d9d9f14c60f88f45f87&storehouseId=3
	 */
	@PostMapping("/remote/check")
	public Boolean storageInventoryCheck(@RequestBody RemoteClearStorehouseCheckRequest remoteClearStorehouseCheckRequest , HttpServletRequest request){
		
		String salt = request.getParameter("salt") ; 
		Preconditions.checkArgument(StrUtil.isNotBlank(salt), "认证标识不存在...");
		
		String md5 = SecureUtil.md5(SecureUtil.md5("check"));
		Preconditions.checkArgument(StrUtil.equalsIgnoreCase(salt, md5), "访问标识salt不正确...");
		
		String storehouseId = request.getParameter("storehouseId");
		Preconditions.checkArgument(StrUtil.isNotBlank(storehouseId), "认证标识不存在...");
		
		remoteClearStorehouseCheckRequest.setStorehouseId(Long.parseLong(storehouseId));
		
		storehouseService.remoteCheck(remoteClearStorehouseCheckRequest);
		
		return Boolean.TRUE;
	}
	
	public static void main(String[] args) {
		System.out.println(SecureUtil.md5("check"));
	}
}
